<?php
/**
 * 阿里云
 */
declare(strict_types=1);
namespace app\api\controller;

use app\common\controller\Api;

use AlibabaCloud\SDK\Ocrapi\V20210707\Ocrapi;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Ocrapi\V20210707\Models\RecognizeIdcardRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class Aliyuns extends Api {

    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Ocrapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/ocr-api
        $config->endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new Ocrapi($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args){
        // 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例使用环境变量获取 AccessKey 的方式进行调用，仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $client = self::createClient(config('aliyun.AccessKeyID'), config('aliyun.AccessKeySecret'));
        $recognizeIdcardRequest = new RecognizeIdcardRequest([
            "url" => $args
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $return = $client->recognizeIdcardWithOptions($recognizeIdcardRequest, $runtime);
            if ($return->statusCode == 200) {
                $idcardDatas = json_decode($return->body->data, true);
                $idcardData = $idcardDatas['data']["face"]["data"];
                return $idcardData;
            }
        }
        catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 错误 message
            var_dump($error->message);
            // 诊断地址
            var_dump($error->data["Recommend"]);
            Utils::assertAsString($error->message);
        }
    }

    public function index() {
        $urls = $this->request->post('url');
        if (!empty($urls)) {
            $path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
            if (file_exists($path)) {
                require_once $path;
            }
            // $urls = "http://pro-system.nmgfdkj.com/uploads/user/user_33/20231214qnmdZzNO.png";
            $data = Aliyuns::main(config("app_url") . $urls);
            if (!empty($data)) {
                $this->success("身份证识别成功", $data);
            } else {
                $this->error("身份证识别失败");
            }
        } else {
            $this->error("未上传身份证照片");
        }
    }
}
